package com.hnucm.c201901020241.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.TextView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.diegodobelo.expandingview.ExpandingItem;
import com.diegodobelo.expandingview.ExpandingList;
import com.google.android.material.tabs.TabLayout;
import com.hnucm.c201901020241.discuss.Disscuss_item;
import com.hnucm.c201901020241.R;
import com.hnucm.c201901020241.my.Update_name;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

public class DisscussFragment extends Fragment{
    DrawerLayout drawerLayout;
    private ExpandingList mExpandingList;
    private TabLayout tabLayout;
    private String TAG = DisscussFragment.class.getSimpleName();
    private ViewPager viewPager;
    Boolean isselected=false;
//    是否初始化成功


    private Fragment[] mFragmentArrays = new Fragment[3];

    private String[] mTabTitles = new String[3];
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.i("discuss","我被创建了");
        return inflater.inflate(R.layout.fragment_disscuss, container, false);
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
//可见时执行的操作
//            点击了当前的页面
            isselected=true;
            Log.i("main1","是我");
        }else{
            isselected=false;
            Log.i("main1","不是我");
//不可见时执行的操作
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        主屏幕的各个部分的设计
        tabLayout = getActivity().findViewById(R.id.tablayout);
        viewPager = (ViewPager) getActivity().findViewById(R.id.tab_viewpager);
        initView();
//左边区域的设计
        drawerLayout=getActivity().findViewById(R.id.drawerlayout);
        getActivity().findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出左边的区域
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
//        点击关闭
        getActivity().findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawer(Gravity.LEFT);
            }
        });
        mExpandingList = getActivity().findViewById(R.id.expanding_list_main);
        createItems();
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("user",getActivity().MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("init1",true);
        editor.putBoolean("init2",true);
        editor.putBoolean("init3",true);
        editor.putBoolean("init4",false);
        editor.commit();

        Boolean init=sharedPreferences.getBoolean("init2",false);
        Boolean isfirst=sharedPreferences.getBoolean("isfirst2",false);
        Log.i("main1",""+init+" "+isfirst+" "+isselected);
        if(init&&!isfirst&&isselected){
            init_NewbieGuide();
            editor.putBoolean("isfirst2",true);
            editor.commit();
        }
    }

    private void init_NewbieGuide() {
        Animation enterAnimation = new AlphaAnimation(0f, 1f);
        enterAnimation.setDuration(600);
        enterAnimation.setFillAfter(true);

        Animation exitAnimation = new AlphaAnimation(1f, 0f);
        exitAnimation.setDuration(600);
        exitAnimation.setFillAfter(true);

        NewbieGuide.with(this)
                .setLabel("Discussfragment")//设置引导层标示区分不同引导层，必传！否则报错
                .setShowCounts(1)
                .setOnGuideChangedListener(new OnGuideChangedListener() {//引导层显示监听
                    @Override
                    public void onShowed(Controller controller) {
                        Log.e(TAG, "NewbieGuide onShowed: ");
                        //引导层显示
                    }

                    @Override
                    public void onRemoved(Controller controller) {//引导层隐藏监听
                        Log.e(TAG, "NewbieGuide  onRemoved: ");
                        //引导层消失（多页切换不会触发）
                    }
                })
                .setOnPageChangedListener(new OnPageChangedListener() {//引导页切换监听
                    @Override
                    public void onPageChanged(int page) {
                        Log.e(TAG, "NewbieGuide  onPageChanged: " + page);
                        //引导页切换，page为当前页位置，从0开始
                    }
                })
                .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                /**
                 * 添加引导页一
                 */
                .addGuidePage(//添加一页引导页
                        GuidePage.newInstance()//创建一个实例
                                .addHighLight(tabLayout)//添加高亮的view
                                .addHighLight(tabLayout, HighLight.Shape.RECTANGLE)
                                .setLayoutRes(R.layout.discussfragment_style)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )

                /**
                 * 添加引导页二
                 */
                .addGuidePage(
                        GuidePage.newInstance()
                                .addHighLight(getActivity().findViewById(R.id.tab_viewpager), HighLight.Shape.RECTANGLE, 20)
                                .setLayoutRes(R.layout.discussfragment_style2) //引导页布局，点击跳转下一页或者消失引导层的控件id
                                .setEverywhereCancelable(true)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                                        .setBackgroundColor(getResources().getColor(R.color.colorAccent))//设置背景色，建议使用有透明度的颜色
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画*/
                )
                .addGuidePage(
                        GuidePage.newInstance()
                        .addHighLight(getActivity().findViewById(R.id.imageView),HighLight.Shape.RECTANGLE)
                        .setLayoutRes(R.layout.discussfragment_style3)
                        .setEnterAnimation(enterAnimation)
                        .setExitAnimation(exitAnimation)
                )
                /**
                 * 展示
                 */
                .show();//显示引导层(至少需要一页引导页才能显示)
    }

    private void initView() {
        mTabTitles[0] = "全站热点";
        mTabTitles[1] = "分区热点";
        mTabTitles[2] = "热点通知";
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        //设置tablayout距离上下左右的距离
        //tab_title.setPadding(20,20,20,20);
        mFragmentArrays[0] = TabFragment.newInstance(mTabTitles[0]);
        mFragmentArrays[1] = TabFragment.newInstance(mTabTitles[1]);
        mFragmentArrays[2] = TabFragment.newInstance(mTabTitles[2]);
        PagerAdapter pagerAdapter = new MyViewPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        //将ViewPager和TabLayout绑定
        tabLayout.setupWithViewPager(viewPager);



//        增加缓存
        viewPager.setOffscreenPageLimit(2);
    }




    final class MyViewPagerAdapter extends FragmentPagerAdapter {

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public long getItemId(int position) {
            return mFragmentArrays[position].hashCode();
        }

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentArrays[position];
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            return mFragmentArrays.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabTitles[position];
        }
    }


    private void createItems() {
        addItem("校园热议", new String[]{"失物招领", "跳蚤市场", "捞人表白"}, R.color.pink, R.drawable.ic_ghost,"a碟");
        addItem("学术研究", new String[]{"医学与健康", "基金", "讲座","古今中国","中医知识"}, R.color.blue, R.drawable.ic_ghost,"b碟");
        addItem("电脑网络", new String[]{"苹果","笔记本","华为","网络技术","硬件设备"}, R.color.purple, R.drawable.ic_ghost,"c碟");
        addItem("休闲娱乐", new String[]{"剧本杀","狼人杀","动漫","美食","旅游"}, R.color.orange, R.drawable.ic_ghost,"e碟");
        addItem("校务特区", new String[]{"校长信箱", "信科院","针推院","医学院","护理学院","文管院","研究生院","湘杏学院"}, R.color.green, R.drawable.ic_ghost,"f碟");
        addItem("实习推荐", new String[]{"计算机实习", "中医实习", "临床实习"}, R.color.blue, R.drawable.ic_ghost,"g碟");
        addItem("社团招新", new String[]{"吉他协会", "志愿者协会", "针灸推拿协会","轮滑社","电影社"}, R.color.yellow, R.drawable.ic_ghost,"h碟");
        addItem("课程特区", new String[]{"选修课", "专业课"}, R.color.purple, R.drawable.ic_ghost,"i碟");
    }

    private void addItem(String title, String[] subItems, int colorRes, int iconRes ,String people) {
        //Let's create an item with R.layout.expanding_layout
//        创建小布局
        final ExpandingItem item = mExpandingList.createNewItem(R.layout.expanding_layout);

        //If item creation is successful, let's configure it
        if (item != null) {
            item.setIndicatorColorRes(colorRes);
            item.setIndicatorIconRes(iconRes);
            //It is possible to get any view inside the inflated layout. Let's set the text in the item
            ((TextView) item.findViewById(R.id.title)).setText(title);
            ((TextView)item.findViewById(R.id.content_item)).setText(people);

            //We can create items in batch.
            item.createSubItems(subItems.length);
            for (int i = 0; i < item.getSubItemsCount(); i++) {
                //Let's get the created sub item by its index
                final View view = item.getSubItemView(i);

                //Let's set some values in
                configureSubItem(item, view, subItems[i]);
            }
//            增加列的点击事件
//            item.findViewById(R.id.add_more_sub_items).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    showInsertDialog(new OnItemCreated() {
//                        @Override
//                        public void itemCreated(String title) {
//                            View newSubItem = item.createSubItem();
//                            configureSubItem(item, newSubItem, title);
//                        }
//                    });
//                }
//            });

//删除列的点击事件
//            item.findViewById(R.id.remove_item).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    mExpandingList.removeItem(item);
//                }
//            });
        }
    }

    //    设置里面的属性列
    private void configureSubItem(final ExpandingItem item, final View view, String subTitle) {
        ((TextView) view.findViewById(R.id.sub_title)).setText(subTitle);
//        删除列中的属性值
//        view.findViewById(R.id.remove_sub_item).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                item.removeSubItem(view);
//            }
//        });
        view.findViewById(R.id.sub_item).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(subTitle);
                Intent intent=new Intent(getActivity(), Disscuss_item.class);
//                根据title弹出相应的论坛
                intent.putExtra("title",subTitle);
                startActivity(intent);
                //getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_in_left);

            }
        });

    }


//    弹出增加提示框，暂时用不到
    private void showInsertDialog(final OnItemCreated positive) {
        final EditText text = new EditText(getContext());
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(text);
        builder.setTitle(R.string.enter_title);
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                positive.itemCreated(text.getText().toString());
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    interface OnItemCreated {
        void itemCreated(String title);
    }
}